package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func CORS(ctx *gin.Context) {

	ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
	ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
	ctx.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

	if ctx.Request.Method == "OPTIONS" {
		ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		ctx.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

		ctx.AbortWithStatus(204)
		return
	}
	ctx.Next()
}

func CORS1(ctx *gin.Context) {
	// preflight
	// AllowMethods := []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
	// AllowHeaders := []string{"Origin", "Content-Length", "Content-Type"}
	if ctx.Request.Method == http.MethodOptions {
		h := ctx.Writer.Header()
		h["Access-Control-Allow-Headers"] = []string{"Origin,Content-Length,Content-Type"}
		h["Access-Control-Allow-Methods"] = []string{"GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS"}
		h["Access-Control-Allow-Origin"] = []string{"*"}
		h["Access-Control-Max-Age"] = []string{"43200"}
		ctx.AbortWithStatus(http.StatusNoContent)
		return
	}

	ctx.Next()
}
